import { createRouter, createWebHashHistory, useRouter } from "vue-router";
// 1. 创建路由规则
const routes = [
  // 重定向
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login/index.vue"),
  },
  {
    path: "/",
    name: "layout",
    component: () => import("../views/layout/index.vue"),
    children: [
      {
        path: "/study",
        name: "study",
        component: () => import("../views/study/index.vue"),
      },
      {
        path: "/detail",
        name: "detail",
        component: () => import("../views/study/detail.vue"),
      },
      {
        path: "/practice",
        name: "practice",
        component: () => import("../views/practice/index.vue"),
        children: [
          {
            path: "/practiceChapter",
            name: "practiceChapter",
            component: () => import("../views/practice/practiceChapter.vue"),
          },
          {
            path: "/practicing",
            name: "practicing",
            component: () => import("../views/practice/practicing.vue"),
          },
        ],
      },
      {
        path: "/pk",
        name: "pk",
        component: () => import("../views/pk/index.vue"),
        children: [
          {
            path: "/connect",
            name: "connect",
            component: () => import("../views/pk/connect.vue"),
          },
          {
            path: "/waiting",
            name: "waiting",
            component: () => import("../views/pk/waiting.vue"),
          },
          {
            path: "/pking",
            name: "pking",
            component: () => import("../views/pk/pking.vue"),
          },
          {
            path: "/pkResult",
            name: "pkResult",
            component: () => import("../views/pk/pkResult.vue"),
          },
        ],
      },
      {
        path: "/user",
        name: "user",
        component: () => import("../views/user/index.vue"),
      },
      {
        path: "/userEdit",
        name: "userEdit",
        component: () => import("../views/user/edit.vue"),
      },
      {
        path: "/changePassword",
        name: "changePassword",
        component: () => import("../views/user/changePassword.vue"),
      },
      {
        path: "/help",
        name: "help",
        component: () => import("../views/user/help.vue"),
      },
    ],
  },
];
// 2. 创建路由实例
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 挂载路由守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next是个函数，表示放行 next('/login') 强制跳转
  if (to.path === "/login") return next();
  // 获取到token
  const tokenStr = window.localStorage.getItem("token");
  if (!tokenStr) return next("/login");
  next();
});

export default router;
// 3. 创建登录组件
// 4. 指定出口
